<script setup lang="ts" name="app">
import { watch, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import dataStore from '@/store/modules/store.js';

const route = useRoute();
const router = useRouter();
const store = dataStore();

// 初始化缓存列表
const state = reactive({
  includeList: ['about'] // 需要缓存的组件名称
});

// 将初始缓存组件添加到缓存目录
state.includeList.forEach((item) => {
  store.addCacheRoute(item);
});

// 监听路由变化
watch(
  () => route,
  (newVal) => {
    const historyState = router.options.history.state;
    if (historyState.forward) {
      // 前进操作
      store.handleForward({
        name: newVal.name,
        path: newVal.path
      });
    } else if (historyState.back) {
      // 后退操作
      store.handleBack({
        name: newVal.name,
        path: newVal.path
      });
    }
  },
  { deep: true }
);
</script>

<template>
  <div class="container">
    <router-view v-slot="{ Component }">
      <keep-alive :include="store.routeName">
        <component :is="Component" />
      </keep-alive>
    </router-view>
  </div>
</template>
